package com.scalar.chiptrack.finance.proformainvoice.actions;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.finance.proformainvoice.forms.ProformaInvoiceSendMailForm;
import com.scalar.chiptrack.finance.proformainvoice.ProformaInvoiceHelper;
import com.scalar.chiptrack.finance.proformainvoice.ProformaInvoiceSendMail;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.Mailer;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.commons.SessionKeys;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.AddressException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.ArrayList;

public class ProformaInvoiceSendMailAction extends ChipTrackAction
{
    public ActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
    {

        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) { }

        HashMap info        = new HashMap ();
        HashMap errors      = new HashMap ();
        HttpSession session = request.getSession ();

        request.setAttribute ( SessionKeys.INFO_MESSAGES, info );
        request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );

        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );

        ActionForward actionForward  = mapping.findForward( "success" );

        ProformaInvoiceSendMailForm sendMailForm = ( ProformaInvoiceSendMailForm ) form;
        String mimeType                     = sendMailForm.getAttachMIMEType ();

        String action 				        = request.getParameter( "action" );
        String processType 				    = request.getParameter( "processType" );
        String invoiceId    		        = request.getParameter( "invoiceId" );
        String invoiceNo    		        = request.getParameter( "invoiceNo" );
        int invoiceIdInt                    = -1;
        boolean success                     = false;

        //System.out.println("ProformaInvoiceSendMailAction.execute --- action = " + action + " invoiceId =  " + invoiceId + " invoiceNo = " + invoiceNo );

        try
        {
            invoiceIdInt = Integer.parseInt( invoiceId );
        }
        catch( NumberFormatException nfe ){ invoiceIdInt = -1; }

        /*if ( user == null )
        {
            user = ( User ) session.getAttribute ( "ExtUser" );
            if ( user == null ) //todo need to forward to the respective user login page
            {
                session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, "/bumpAssmMail.do?" + request.getQueryString () );
                return ( mapping.findForward ( "login" ) );
            }
        }*/
        // Don't redirect to Login page.. show same page with 'session timeout' message.
        if ( user == null )
		{
            request.setAttribute ( "closeWindowAfterSessionExp", "true" );
			return ( mapping.findForward( "success" ) );
		}

        //String userFrom = ConfigManager.getSysAdminEmail();

        if ( ( mimeType == null ) || ( mimeType.trim ().length () == 0 ) )
        {
            mimeType = "PDF";
            sendMailForm.setAttachMIMEType ( "PDF" );
        }

        try
        {
            if ( ( action != null ) && ( action.equalsIgnoreCase ( "save" ) ) )
            {
                try
                {
                    String isConfirm                = null;
                    String sysAdminEmail            = null;
                    String companyEmailId           = null;
                    String to                       = "";
                    String cc                       = "";
                    String bcc                      = "";
                    String message                  = "";
                    String host                     = "";
                    String subject                  = "";

                    to  = extractRecipientEmailAsString( sendMailForm.getToRecipientsEmailsList() );
                    cc  = extractRecipientEmailAsString( sendMailForm.getCcRecipientsEmailsList() );
                    bcc = extractRecipientEmailAsString( sendMailForm.getBccRecipientsEmailsList() );

                    isConfirm = ( String ) session.getAttribute ( "isConfirm" );

                    sysAdminEmail   = ConfigManager.getSysAdminEmail();
                    companyEmailId  = sysAdminEmail.substring ( sysAdminEmail.indexOf ( "@" ) + 1, sysAdminEmail.length () );

                    if ( isConfirm == null )
                    {
                        String emailIds = "";
                        if ( to != null )
                        {
                            if( emailIds != null && emailIds.trim().length() == 0 )
                            {
                                emailIds = extractingAndValidatingEmails( to, companyEmailId );
                            }
                            else
                            {
                                emailIds = emailIds + ", " + extractingAndValidatingEmails( to, companyEmailId );
                            }
                        }
                        if ( cc != null )
                        {
                            if( emailIds != null && emailIds.trim().length() == 0 )
                            {
                                emailIds = extractingAndValidatingEmails( cc, companyEmailId );
                            }
                            else
                            {
                                emailIds = emailIds + ", " + extractingAndValidatingEmails( cc, companyEmailId );
                            }
                        }
                        if ( bcc != null )
                        {
                            if( emailIds != null && emailIds.trim().length() == 0 )
                            {
                                emailIds = extractingAndValidatingEmails( bcc, companyEmailId );
                            }
                            else
                            {
                                emailIds = emailIds + ", " + extractingAndValidatingEmails( bcc, companyEmailId );
                            }
                        }

                        if ( emailIds.trim().length () > 0 )
                        {
                            errors.put ( "The following e-mails are going out of the company. Please confirm to send them.", null );

                            info.put ( "Emails ", emailIds );

                            session.setAttribute ( "isConfirm", "true" );

                            return mapping.findForward ( "success" );
                        }
                    }

                    message     = sendMailForm.getMessage();
                    subject     = sendMailForm.getSubject();

                    ProformaInvoiceHelper.sendPrformaInvoiceNotifications( sendMailForm.getInvoiceId(), subject, message, to, cc, bcc, sendMailForm.getAttachMIMEType(), request, user.getFirstName(), sendMailForm.getFromUser() );

                    success = true;
                    info.put ( "Email has been sent successfully", null );
                }
                catch ( Exception se )
                {
                    success = false;
                    String errMessage = "Internal Server Error";
                    errors.put ( errMessage, "Could not send Email" );
                    session.removeAttribute ( "isConfirm" );
                    se.printStackTrace ();
                }
                request.setAttribute( "proformaInvoiceMailSuccessfullySent", "true" );
                session.removeAttribute ( "isConfirm" );
                return ( mapping.findForward ( "sendMailView" ) );
            }
            else if ( ( action != null ) && ( action.equalsIgnoreCase ( "addMore" ) ) )
            {
                String recipientType    = request.getParameter( "recipientType" );
                String controlIndex     = request.getParameter( "controlIndex" );

                com.scalar.chiptrack.finance.proformainvoice.ProformaInvoiceSendMail sendMail= null;
                if( "toUsers".equalsIgnoreCase( recipientType ) )
                {
                    sendMail = new ProformaInvoiceSendMail();
                    sendMail.setEmailUser( "" );
                    sendMailForm.getToRecipientsEmailsList().add( sendMail );
                }
                else if( "ccUsers".equalsIgnoreCase( recipientType ) )
                {
                    sendMail = new ProformaInvoiceSendMail();
                    sendMail.setEmailUser( "" );
                    sendMailForm.getCcRecipientsEmailsList().add( sendMail );
                }
                else if( "bccUsers".equalsIgnoreCase( recipientType ) )
                {
                    sendMail = new ProformaInvoiceSendMail();
                    sendMail.setEmailUser( "" );
                    sendMailForm.getBccRecipientsEmailsList().add( sendMail );
                }

                return ( mapping.findForward ( "success" ) );
            }
            else
            {

                ProformaInvoiceHelper.resetProformaInvoiceMailForm( sendMailForm );

                ArrayList toMailsList       = new ArrayList();
                ArrayList ccMailsList       = new ArrayList();
                ArrayList bbcMailsList      = new ArrayList();

                ProformaInvoiceSendMail toSendMail  = null;
                ProformaInvoiceSendMail ccSendMail  = null;
                ProformaInvoiceSendMail bccSendMail = null;

                //TODO NEED TO LOAD NOTIFICATION EMAIL FROM CONFIGMANAGER -KP

                toSendMail = new ProformaInvoiceSendMail();
                toSendMail.setEmailUser( "" );
                toMailsList.add( toSendMail );
                sendMailForm.setToRecipientsEmailsList( toMailsList );

                ccSendMail = new ProformaInvoiceSendMail();
                ccSendMail.setEmailUser( "" );
                ccMailsList.add( ccSendMail );
                sendMailForm.setCcRecipientsEmailsList( ccMailsList );

                bccSendMail = new ProformaInvoiceSendMail();
                bccSendMail.setEmailUser( "" );
                bbcMailsList.add( bccSendMail );
                sendMailForm.setBccRecipientsEmailsList( bbcMailsList );

                sendMailForm.setInvoiceId ( invoiceIdInt );
                sendMailForm.setInvoiceNo ( invoiceNo );
                sendMailForm.setProcessType ( processType );

                sendMailForm.setSubject( "Proforma Invoice # " + sendMailForm.getInvoiceNo() );

                sendMailForm.setFromUser( user.getEmail() );

                if( ccSendMail.getEmailUser() != null && ccSendMail.getEmailUser().trim().length() > 0 )
                {
                    sendMailForm.setDivCcDisplayStyle( "CLASS='LINKSON'" );
                }
                else
                {
                    sendMailForm.setDivCcDisplayStyle( "CLASS='LINKSOFF'" );
                }

                sendMailForm.setDivBccDisplayStyle( "CLASS='LINKSOFF'" );

                session.removeAttribute ( "isConfirm" );
            }
        }
        catch( Exception e )
        {
            actionForward = mapping.findForward( "success" );
            e.printStackTrace();
            errors.put ("Could not load the proforma Invoice send mail page", null );
        }
        return actionForward;
    }

    public static String extractingAndValidatingEmails( String recipientEmails, String companyEmailId )
    {
        InternetAddress[] internetAddresses = null;
        InternetAddress internetAddress     = null;
        String address                      = "";
        String emailIds                     = "";

        if ( recipientEmails != null )
        {
            try
            {
                internetAddresses = InternetAddress.parse ( recipientEmails );
            } catch (AddressException e) { }

            for ( int i = 0; i < internetAddresses.length; i++ )
            {
                internetAddress = internetAddresses[i];
                address         = internetAddress.getAddress();
                if ( address.indexOf ( companyEmailId ) == -1 )
                {
                    if( emailIds == "" )
                    {
                        emailIds = emailIds + internetAddress.getAddress () ;
                    }
                    else
                    {
                        emailIds = emailIds + ", " + internetAddress.getAddress () ;
                    }
                }
            }
        }

        return emailIds;
    }

    public static String extractRecipientEmailAsString( ArrayList recipientEmailList )
    {
        com.scalar.chiptrack.finance.proformainvoice.ProformaInvoiceSendMail sendMail = null;
        String emailUserAsString        = "";
        if( recipientEmailList != null && recipientEmailList.size() > 0 )
        {
            for( int i = 0; i < recipientEmailList.size(); i++ )
            {
                sendMail = (com.scalar.chiptrack.finance.proformainvoice.ProformaInvoiceSendMail) recipientEmailList.get( i );
                if( sendMail.getEmailUser() != null && sendMail.getEmailUser().trim().length() > 0 )
                {
                    if( emailUserAsString.trim().length() == 0 )
                    {
                        emailUserAsString = sendMail.getEmailUser();
                    }
                    else
                    {
                        if ( emailUserAsString.indexOf ( sendMail.getEmailUser() ) == -1 )
                        {
                            emailUserAsString = emailUserAsString + ", " + sendMail.getEmailUser();
                        }
                    }
                }
            }
        }
        if ( emailUserAsString.endsWith( Mailer.EMAIL_SEPARATOR ) )
        {
            emailUserAsString = emailUserAsString.substring( 0, ( emailUserAsString.length() - 1 ) );
        }

        return  emailUserAsString;
    }

}
